/**
 * 
 */
package hu.gbalage.directories.jdo;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import hu.gbalage.directories.IDirectory;
import hu.gbalage.directories.IEntry;
import hu.gbalage.owl.cms.disec.PMF;

/**
 * @author balage
 *
 */
public class JDORootDir implements IDirectory {

	@SuppressWarnings("unchecked")
	public static List<JDOEntryData> listChildren(Long parent){
		PersistenceManager pm = PMF.getManager();
		
		Query query = pm.newQuery(JDOEntryData.class);
		query.setFilter("parent == parentid");
		query.declareParameters("parentid");
		
		List<JDOEntryData> eds = (List<JDOEntryData>) query.execute(parent);
		
		pm.close();
		return eds;
	}
	
	public static boolean addChild(JDOEntryData parent, IEntry entry){
		IEntryProvider ep = EntryProviderFactory.createEntryProviderFor(entry);

		if (ep == null) return false;
		
		PersistenceManager pm = PMF.getManager();
		
		JDOEntryData ed = new JDOEntryData();
		ed.entry = ep;
		ed.name = entry.getName();
		ed.parent = (parent != null) ? parent.id : -1l;
		pm.makePersistent(ed);
		
		
		pm.close();
		
		return false;
	}
	
	@SuppressWarnings("unchecked")
	public static JDOEntryData load(Long id){
		PersistenceManager pm = PMF.getManager();
		
		Query query = pm.newQuery(JDOEntryData.class);
		query.setFilter("id == dirid");
		query.declareParameters("dirid");
		
		List<JDOEntryData> eds = (List<JDOEntryData>) query.execute(id);
		
		pm.close();
		
		if (eds.isEmpty()) return null;
		return eds.get(0);
	}
	
	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IDirectory#getChildren()
	 */
	@Override
	public List<IEntry> getChildren() {
		
		ArrayList<IEntry> es = new ArrayList<IEntry>();
		for(JDOEntryData ed : listChildren(-1l))
			es.add(ed.entry.getEntry());
		
		return es;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IDirectory#put(hu.gbalage.directories.IEntry)
	 */
	@Override
	public boolean put(IEntry entry) {
		
		return addChild(null, entry); 
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#getName()
	 */
	@Override
	public String getName() {
		return "jdo";
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#getParent()
	 */
	@Override
	public IDirectory getParent() {
		return null;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#isDirectory()
	 */
	@Override
	public boolean isDirectory() {
		return true;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#isFile()
	 */
	@Override
	public boolean isFile() {
		return false;
	}

}
